/**
 * 
 */
package com.res.simulator.handler;

import java.text.DateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.res.common.handler.CommonHandler;
import com.res.simulator.model.CatalogManagementControlModel;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.simulator.transformer.APISearchTransformer;
import com.res.simulator.view.CatalogManagementView;
import com.res.system.utils.SimulatorUtilities;
import com.res.system.utils.SimulatorUtilities.ConfigData;
import com.sip.comserver.communication.CommunicationMessage;
import com.sip.comserver.communication.utils.CommonUtils;

/**
 * CatalogManagementHandler
 */
public class CatalogManagementHandler implements CommonHandler<CatalogManagementView, CatalogManagementControlModel> {

	private static final Logger logger = Logger.getLogger(CatalogManagementHandler.class);

	public CatalogManagementView process(final CatalogManagementControlModel model) throws Exception {

		final CommunicationMessage message = extract(model);

		final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
		final CommunicationMessage returnedMessage = plugin.invoke(message);

		logger.info("Recieced message==> :" + returnedMessage.getMessageHeader());
		logger.info("Recieced message==> :" + returnedMessage.getMessageBody());
		logger.info("Recieced message==> :" + returnedMessage.getObject().toString());
		System.out.println("input String====================>" + model.getInputParameter());

		final CatalogManagementView view = new CatalogManagementView();

		view.setApiName(model.getSelectedAPI());

		// ====
		String messageBody = returnedMessage.getMessageBody();
		String valueText = "";
		if (!messageBody.contains("Configuration Issue")) {
			if (messageBody.contains("Result")) {
				messageBody = messageBody.substring(0, messageBody.indexOf(("Result:")));
			}

			String[] data = messageBody.split("\\|");
			for (String text : data) {
				valueText += " " + text;
			}
		}
		// ===

		view.setInputValueString(valueText);

		String outputMessage = returnedMessage.getMessageBody();
		String result = null;
		result = getResultValue(outputMessage, result);

		view.setResult(result);

		final String fileName = generateFileName(returnedMessage.getMessageBody());
		final CommonFileHandler fileHandler = new CommonFileHandler();

		final String fileUrl = fileHandler.save((String) returnedMessage.getObject(), fileName);

		System.out.println("File name=========>" + fileName);
		System.out.println("File url==========>" + fileUrl);

		view.setLocation(fileUrl);

		return view;
	}

	/**
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	private CommunicationMessage extract(final CatalogManagementControlModel model) throws Exception {

		final CommunicationMessage message = new CommunicationMessage();

		final String selectedAPI = model.getSelectedAPI();
		final String apiCatagory = model.getApiCategory();

		String inputParamString = model.getInputParameter();
		inputParamString = inputParamString.concat("|API:" + selectedAPI);

		final String serverAddress = SimulatorUtilities.getConfigData(ConfigData.SERVER_ADDRESS);
		final String port = SimulatorUtilities.getConfigData(ConfigData.SERVER_PORT);

		String executorKey = "cm." + apiCatagory + "." + selectedAPI;
		logger.info("executorKey==>" + executorKey.toLowerCase());
		String executorName = SimulatorUtilities.getExecutorName(executorKey.toLowerCase());
		logger.info("executor Name==>" + executorName);

		// ============================================================================================================
		// NOTE Executor name is hard coded-GetEligibleOffersExecutor TODO-
		// HardCoded executor name need to be removed.
		executorName = "GetEligibleOffersExecutor";
		// ==============================================================================================================
		logger.info("Message Header==>" + "JOBType:cm" + "|ID:" + serverAddress + "|Port:" + port + "|Executor:" + executorName);

		message.setMessageHeader("JOBType:cm|Executor:" + executorName + "|ID:" + serverAddress + "|Port:" + port);

		message.setMessageBody(inputParamString);

		System.out.println("Print Pass message body .. " + message.getMessageBody());
		return message;
	}

	/**
	 * @param outputMessage
	 * @param result
	 * @return
	 */
	private String getResultValue(String outputMessage, String result) {

		if (outputMessage.contains("Result:")) {
			String resultString = outputMessage.substring(outputMessage.indexOf(("Result:")));

			try {
				result = CommonUtils.find(resultString, "Result");

			} catch (Exception e) {
				System.out.println("exception-" + e.toString());

			}

		}
		return result;
	}

	private String generateFileName(final String valueString) throws Exception {

		final Date now = new Date();
		final String dateTime = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now);

		// final String channel = CommonUtils.find(valueString, "SIM_CHANNEL");
		final String channel = "CM_";

		final String fileName = channel + "-" + now.getTime() + ".xml";

		return fileName;
	}

}
